/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */
package com.pig4cloud.pigx.wallet.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pigx.common.core.constant.SecurityConstants;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.common.customize.utils.BigDecimalUtils;
import com.pig4cloud.pigx.common.customize.i18n.util.MessageUtils;
import com.pig4cloud.pigx.common.data.resolver.DictResolver;
import com.pig4cloud.pigx.system.dto.ArticleInformationDTO;
import com.pig4cloud.pigx.user.entity.User;
import com.pig4cloud.pigx.wallet.api.feign.RemoteRippleUserService;
import com.pig4cloud.pigx.wallet.constant.WalletConstant;
import com.pig4cloud.pigx.wallet.constant.WalletStatusEnum;
import com.pig4cloud.pigx.wallet.dto.ChargeMentionNotificationDTO;
import com.pig4cloud.pigx.wallet.entity.CapitalAccount;
import com.pig4cloud.pigx.wallet.entity.Notification;
import com.pig4cloud.pigx.wallet.entity.RechargeRecord;
import com.pig4cloud.pigx.wallet.mapper.CapitalAccountMapper;
import com.pig4cloud.pigx.wallet.mapper.RechargeRecordMapper;
import com.pig4cloud.pigx.wallet.mapstruct.NotificationStruct;
import com.pig4cloud.pigx.wallet.service.CapitalAccountService;
import com.pig4cloud.pigx.wallet.service.NotificationService;
import com.pig4cloud.pigx.wallet.utils.WalletEmailSender;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 资金账户
 *
 * @since 2022-08-12 19:28:20
 */
@Service
@RequiredArgsConstructor
public class CapitalAccountServiceImpl extends ServiceImpl<CapitalAccountMapper, CapitalAccount> implements CapitalAccountService {

	/**
	 * 充值记录
	 */
	private final RechargeRecordMapper rechargeRecordMapper;

	/**
	 * 邮件发送器
	 */
	private final WalletEmailSender walletEmailSender;

	/** 用户消息通知 */
	private final NotificationService notificationService;

	/**
	 * ripple-user-biz 模块feign接口
	 */
	private final RemoteRippleUserService remoteRippleUserService;

	/**
	 * 修改资金账户
	 * @param capitalAccount
	 */
	@Override
	public void updateCapitalAccountById(CapitalAccount capitalAccount) {
		// 查询账户信息
		CapitalAccount capitalAccountInfo = this.getById(capitalAccount.getId());
		// 查询用户信息
		R<User> userInfo = remoteRippleUserService.getUserByUserId(capitalAccount.getUserId(), SecurityConstants.FROM_IN);

		// 生成充值记录
		RechargeRecord rechargeRecord = new RechargeRecord();
		rechargeRecord.setId(IdUtil.getSnowflakeNextId());
		// 用户id
		rechargeRecord.setUserId(capitalAccount.getUserId());
		// 数量 = 修改可用 - 账户可用
		rechargeRecord.setQuantity(capitalAccount.getAvailable().subtract(capitalAccountInfo.getAvailable()));
		// 充值状态（已完成）
		rechargeRecord.setState(WalletStatusEnum.RECHARGE_COMPLETED.getStatus());
		// 创建时间
		rechargeRecord.setCreateTime(LocalDateTime.now());
		// 币种（USDT）
		rechargeRecord.setCurrency(WalletConstant.USDT);
		// 充值类型（系统字典：user_fund_recharge_type）
		rechargeRecord.setType(capitalAccount.getType());
		// 备注
		rechargeRecord.setRemark(capitalAccount.getRemark());
		rechargeRecordMapper.insert(rechargeRecord);

		// 封装充提通知参数
		ChargeMentionNotificationDTO notificationDTO = new ChargeMentionNotificationDTO(rechargeRecord);
		notificationDTO.setLanguage(userInfo.getData().getLanguageCode());
		// 用户消息通知
		Notification notification = NotificationStruct.INSTANCE.chargeMentionDTO2PO(notificationDTO);
		notificationService.save(notification);

		// 修改资金账户
		CapitalAccount capitalAccountUpdate = new CapitalAccount();
		capitalAccountUpdate.setId(capitalAccount.getId());
		// 可用
		capitalAccountUpdate.setAvailable(capitalAccount.getAvailable());
		// 冻结
		capitalAccountUpdate.setFrozen(capitalAccount.getFrozen());
		this.updateById(capitalAccountUpdate);

		// 发送邮件
		ArticleInformationDTO articleInformationDTO = new ArticleInformationDTO();
		articleInformationDTO.setLanguageId(userInfo.getData().getLanguageCode());
		// 标题参数替换
		Map<String, String> titleCode = new HashMap<>();
		// 内容参数替换
		Map<String, String> textContentCode = new HashMap<>();
		// 资金账户充值类型
		titleCode.put("${type}", MessageUtils.getMessageByLocale(DictResolver.getDictItemByItemValueInner("user_fund_recharge_type", capitalAccount.getType()).getRemarks(), MessageUtils.getLocale(userInfo.getData().getLanguageCode()), null));
		textContentCode.put("${type}", MessageUtils.getMessageByLocale(DictResolver.getDictItemByItemValueInner("user_fund_recharge_type", capitalAccount.getType()).getRemarks(), MessageUtils.getLocale(userInfo.getData().getLanguageCode()), null));
		// 数量
		textContentCode.put("${quantity}", BigDecimalUtils.toStrRemoveExtraZero(rechargeRecord.getQuantity()));
		// 当前可用余额
		textContentCode.put("${available}", BigDecimalUtils.toStrRemoveExtraZero(capitalAccount.getAvailable()));
		// 备注
		textContentCode.put("${remark}", capitalAccount.getRemark());
		// 冻结总金额
		textContentCode.put("${frozen}", BigDecimalUtils.toStrRemoveExtraZero(capitalAccount.getFrozen()));
		walletEmailSender.sendRechargeCapitalAccount(titleCode, textContentCode, userInfo.getData().getEmail(),
				articleInformationDTO, capitalAccount.getType());

	}
}
